package cn.ceplc.nlu.admin.controller;

import cn.ceplc.nlu.admin.domain.User;
import cn.ceplc.nlu.admin.security.JwtAuthenticatioToken;
import cn.ceplc.nlu.admin.service.UserService;
import cn.ceplc.nlu.admin.util.PasswordUtils;
import cn.ceplc.nlu.admin.util.SecurityUtils;
import cn.ceplc.nlu.base.model.LoginModel;
import cn.ceplc.nlu.base.result.ExceptionMsg;
import cn.ceplc.nlu.base.result.ResponseData;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class LoginController {


    private final Producer producer;

    private final UserService userService;

    private final AuthenticationManager authenticationManager;


    @Autowired
    public LoginController(Producer producer, UserService userService, AuthenticationManager authenticationManager) {
        this.producer = producer;
        this.userService = userService;
        this.authenticationManager = authenticationManager;
    }


    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 保存到验证码到 session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }


    @PostMapping("/login")
    public ResponseData login(@RequestBody LoginModel loginModel, HttpServletRequest request) throws IOException {
        String username = loginModel.getUsername();
        String password = loginModel.getPassword();
        String captcha = loginModel.getCaptcha();
        // 从session中获取之前保存的验证码跟前台传来的验证码进行匹配
        Object kaptcha = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if(kaptcha == null){
            return new ResponseData(ExceptionMsg.FAILED, "验证码已失效");
        }
        if(!captcha.equals(kaptcha)){
            return new ResponseData(ExceptionMsg.FAILED, "验证码不正确");
        }
        // 用户信息
        User user = userService.findByUserName(username);
        // 账号不存在、密码错误
        if (user == null || !PasswordUtils.matches(user.getSalt(), password, user.getPassword())) {
            return new ResponseData(ExceptionMsg.FAILED, "用户名或密码错误");
        }
        // 系统登录认证
        JwtAuthenticatioToken token = SecurityUtils.login(request, username, password, authenticationManager);
        return new ResponseData(ExceptionMsg.SUCCESS, token);
    }

}
